﻿using System.Collections.Generic;
using UnityEngine;

namespace Component.Tools
{
    public class QueuePool<T> where T : MonoBehaviour
    {
        private static GameObject _poolRoot;
        
        private readonly Queue<T> queue;
        private readonly GameObject prefab;
        private readonly Transform parent;
        
        public QueuePool(GameObject prefab, Transform parent)
        {
            queue = new Queue<T>();
            this.prefab = prefab;
            this.parent = parent;
        }
        /// <summary>
        /// 获取对象：队列为空就Instantiate，否则出列
        /// </summary>
        /// <returns>对象</returns>
        public T GetInstance()
        {
            T t;
            if (queue.Count == 0)
            {
                GameObject go = Object.Instantiate(prefab);
                go.name += Random.Range(0,1000);
                t = go.GetComponent<T>();
                t.transform.parent = parent;
            }
            else
            {
                t = queue.Dequeue();
                t.gameObject.SetActive(true);
                t.transform.parent = parent;
            }

            return t;
        }

        /// <summary>
        /// 将线加入到队列中，并统一设置transform
        /// </summary>
        /// <param name="t">回收的对象</param>
        public void ResetInstance(T t)
        {
            if (_poolRoot == null)
            {
                _poolRoot = GameObject.Find("PoolRoot");
                if (_poolRoot == null)
                {
                    _poolRoot = new GameObject("PoolRoot");
                }
            }
            queue.Enqueue(t);
            t.gameObject.SetActive(false);
            t.transform.parent = _poolRoot.transform;
        }
    }
}